package com.collection.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.collection.api.ApplyAuditService;
import com.collection.api.ApplyDitributionService;
import com.collection.api.ApplyMainService;
import com.collection.api.UBaseService;
import com.collection.api.entity.ApplyAudit;
import com.collection.api.entity.ApplyDitribution;
import com.collection.api.entity.sys.SysRole;
import com.collection.api.entity.sys.SysUser;
import com.collection.api.sys.SysRoleService;
import com.collection.api.entity.sys.SysUser;
import com.collection.api.sys.SysUserService;
import com.collection.dto.RequestDTO;
import com.collection.dto.ResponseDTO;
import com.collection.util.HttpClientUtil;
import com.collection.web.pagination.Page;
import com.collection.web.pagination.PageBuilder;
import com.collection.web.pagination.PageRequest;
import com.collection.web.resolver.annotation.GridParam;
import com.collection.web.shiro.util.ShiroUserUtils;

import net.sf.json.JSONObject;

/**
 * @Description :
 * @author : zongzp
 * @date :2018年1月10日上午9:15:16
 * @version : 1.1.0
 */
@Controller
@RequestMapping("/audit")
public class AuditController {
	@Value("${dcapp.url}")
	private String appUrl;

	@Reference(version = "1.0.0")
	private UBaseService baseService;

	@Reference(version = "1.0.0")
	private SysUserService sysUserService;

	@Reference(version = "1.0.0")
	private ApplyDitributionService applyDitributionService;

	@Reference(version = "1.0.0")
	private ApplyAuditService applyAuditService;

	@Reference(version = "1.0.0")
	private ApplyMainService applyMainService;

	@Reference(version = "1.0.0")
	private SysRoleService sysRoleService;

	private static Logger logger = LoggerFactory.getLogger(AuditController.class);

	/**
	 * @descrption:
	 * @author :ZhangQiuSheng
	 * @Date : 2018年1月10日
	 */
	@RequestMapping("/list")
	public String getUBaseList(HttpServletRequest request, @GridParam PageRequest pageRequest, String name, String idNo,
			String phone, String auditUserId, Integer id, String auditTime1, String auditTime2, String status,
			String realName) {
		logger.info("=========加载审批用户列表===========");
		List<Map<String, Object>> auditorList = getAuditorList();

			List<Map<String, Object>> ubaseList = baseService.selectUbaseAll(name, idNo, phone, auditUserId, id, 
					pageRequest.getOffset(), pageRequest.getPageSize(), auditTime1, auditTime2, status, realName);
			int total = baseService.selectUbaseCount(name, idNo, phone, auditUserId, auditTime1, auditTime2, status, realName);
			Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, ubaseList, total);

			request.setAttribute("page", page);
			request.setAttribute("total", total);
			request.setAttribute("name", name);
			request.setAttribute("phone", phone);
			request.setAttribute("auditTime1", auditTime1);
			request.setAttribute("auditTime2", auditTime2);
			request.setAttribute("auditorList", auditorList);
			request.setAttribute("realName", realName);
			request.setAttribute("status", status);
		 
		return "audit/list";
	}

	/**
	 * @descrption:加载审核员审核的用户
	 * @author :ZhangQiuSheng
	 * @Date : 2018年1月18日
	 */
	@RequestMapping("/auditor")
	public String getUBaseListSH(HttpServletRequest request, @GridParam PageRequest pageRequest, String name,
			String idNo, String phone, String auditUserId, Integer id, String auditTime1, String auditTime2,
			String status, String realName) {
		logger.info("=========加载加载审核员审核列表===========");
		String type ="SH";
		List<Map<String, Object>> auditorList = getAuditorList();

		List<Map<String, Object>> ubaseList = baseService.selectUbaseAllSH(name, idNo, phone, id, 
				pageRequest.getOffset(), pageRequest.getPageSize(), auditTime1, auditTime2, status, realName, type);
		
		int total = baseService.selectUbaseCountSH(name, idNo, phone, auditTime1, auditTime2, status, realName, type);

		Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, ubaseList, total);
		request.setAttribute("page", page);
		request.setAttribute("total", total);
		request.setAttribute("name", name);
		request.setAttribute("phone", phone);
		request.setAttribute("auditTime1", auditTime1);
		request.setAttribute("auditTime2", auditTime2);
		request.setAttribute("auditorList", auditorList);
		request.setAttribute("realName", realName);
		request.setAttribute("status", status);
		return "audit/auditorlist";
	}

	/**
	 * @descrption:加载经理审批的用户
	 * @author :ZhangQiuSheng
	 * @Date : 2018年1月18日
	 */
	@RequestMapping("/auditmanager")
	public String getUBaseListSHM(HttpServletRequest request, @GridParam PageRequest pageRequest, String name,
			String idNo, String phone, String auditUserId, Integer id, String auditTime1, String auditTime2,
			String status, String realName) {
		logger.info("=========加载审批用户列表===========");
		String type = "SHM";
		List<Map<String, Object>> auditorList = getAuditorList();

		List<Map<String, Object>> ubaseList = baseService.selectUbaseAllSH(name, idNo, phone, id,
				pageRequest.getOffset(), pageRequest.getPageSize(), auditTime1, auditTime2, status, realName, type);
		int total = baseService.selectUbaseCountSH(name, idNo, phone, auditTime1, auditTime2, status, realName,type);
		Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, ubaseList, total);

		request.setAttribute("page", page);
		request.setAttribute("total", total);
		request.setAttribute("name", name);
		request.setAttribute("phone", phone);
		request.setAttribute("auditTime1", auditTime1);
		request.setAttribute("auditTime2", auditTime2);
		request.setAttribute("auditorList", auditorList);
		request.setAttribute("realName", realName);
		request.setAttribute("status", status);

		return "audit/auditmanager";
	}

	@RequestMapping("/detail")
	public String getDetail(HttpServletRequest request, int applyId) {
		String phone = "";
		String idno = "";
		String name = "";
		String bankCardNo = "";
		String loginType = ShiroUserUtils.getCurrentShiroUser().getSysUser().getType();
		request.setAttribute("loginType", loginType);
		// 1.获取核桃分，芝麻分，反欺诈分
		// 2.获取体现金额，车辆价值金额，个人信用金额
		// 3.获取车辆评估价格，
		// 4.信用评估价格
		// 5.

		// 获取基本信息
		/*
		 * Map<String, Object> paramMap = new HashMap<String, Object>();
		 * RequestDTO req = new RequestDTO(); paramMap.put("applyId", applyId);
		 * req.setData(paramMap); String baseInfo =
		 * HttpClientUtil.doPostJson(appUrl+"api/audit/applyInfoDetail",
		 * JSON.toJSONString(req)); JSONObject baseInfoJson =
		 * JSONObject.fromObject(baseInfo); JSONObject resultJson =
		 * (JSONObject)baseInfoJson.get("results"); String firstContactsName =
		 * (String)resultJson.get("firstContactsName"); String
		 * firstContactsMobile = (String)resultJson.get("firstContactsMobile");
		 * String secondContractsName
		 * =(String)resultJson.get("secondContractsName"); String
		 * secondContractsMobile =
		 * (String)resultJson.get("secondContractsMobile");
		 */

		// 获取证明材料信息
		/*
		 * Map<String, Object> credentialMap = new HashMap<String, Object>();
		 * RequestDTO req1 = new RequestDTO(); credentialMap.put("phone",
		 * phone); credentialMap.put("idno", idno); credentialMap.put("name",
		 * name); credentialMap.put("bankCardNo", bankCardNo);
		 * req1.setData(credentialMap); String credentialInfo =
		 * HttpClientUtil.doPostJson(appUrl+"api/audit/credential",
		 * JSON.toJSONString(req1)); JSONObject credentialInfoJson =
		 * JSONObject.fromObject(credentialInfo); JSONObject
		 * credentialInfoResultJson =
		 * (JSONObject)credentialInfoJson.get("results");
		 */// ---此处获取证明材料详细信息---

		// 证明材料-获取活体照片接口
		/*
		 * String livingInfo =
		 * HttpClientUtil.doPostJson(appUrl+"api/audit/createCheckReport",
		 * JSON.toJSONString(req)); JSONObject livingInfoJson =
		 * JSONObject.fromObject(livingInfo); JSONObject livingInfoResultJson =
		 * (JSONObject)livingInfoJson.get("results");
		 */// --详细内容--

		// 获取通讯录信息
		/*
		 * String contactList =
		 * HttpClientUtil.doPostJson(appUrl+"api/audit/getContactList",
		 * JSON.toJSONString(req)); JSONObject concatsListJson =
		 * JSONObject.fromObject(baseInfo); JSONObject concatsListresultJson =
		 * (JSONObject)concatsListJson.get("results"); List<Map<String,Object>>
		 * concatsList =
		 * (List<Map<String,Object>>)resultJson.get("concatsList");
		 */

		// 超能盾报告
		/*
		 * String superInfo = HttpClientUtil.doPostJson(appUrl+
		 * "api/audit/superRnergyProtectReport", JSON.toJSONString(req));
		 * JSONObject superInfoJson = JSONObject.fromObject(superInfo);
		 * JSONObject superResultJson =
		 * (JSONObject)superInfoJson.get("results");
		 */// --里面是详细内容--
		request.setAttribute("applyId", applyId);
		return "audit/detail";
	}

	/**
	 * 
	 * @Description :获取审核员列表
	 * @author : zongzp
	 * @date :2018年1月15日下午1:35:09
	 * @version : 1.2.0
	 * @return : List<Map<String,Object>>
	 */
	public List<Map<String, Object>> getAuditorList() {
		String name = "审核员";
		String userType = "SH";
		List<Map<String, Object>> sysUserList = getUserByType(userType, name);
		return sysUserList;
	}

	/**
	 * 
	 * @Description :获取同一个类型的用户
	 * @author : zongzp
	 * @date :2018年1月15日下午1:17:14
	 * @version : 1.2.0
	 * @param userType
	 * @param name
	 * @return : List<SysUser>
	 */

	public List<Map<String, Object>> getUserByType(String userType, String name) {
		List<Map<String, Object>> findUserList = sysUserService.findUserList(null, null, null, userType, null, null);
		return findUserList;
	}

	/**
	 * 
	 * @Description :分配进件给审核员
	 * @author : zongzp
	 * @date :2018年1月15日下午3:03:05
	 * @version : 1.2.0
	 * @param userId
	 * @param applyIds
	 * @return : ResponseDTO
	 */
	@RequestMapping("/distribute")
	@ResponseBody
	public ResponseDTO distributeAuditor(String userId, String applyIds) {
		ResponseDTO responseDTO = new ResponseDTO(null, null);
		int save = 0;
		int update = 0;
		try {
			ArrayList<Integer> pid = new ArrayList<>();
			ApplyDitribution applyDitribution = new ApplyDitribution();
			applyDitribution.setAuditUserId(Integer.valueOf(userId));
			applyDitribution.setDistributionTime(new Date());
			if (StringUtils.isNotBlank(applyIds) && !(applyIds.equals("null"))) {
				String[] cid = applyIds.split(",");
				for (int i = 0; i < cid.length; i++) {
					String c = cid[i];
					applyDitribution.setApplyMainId(Integer.valueOf(c));
					boolean contains = pid.contains(Integer.valueOf(c));
					if (contains) {
						// 更新操作planDistributionBiz
						update += applyDitributionService.updateByPrimaryKey(applyDitribution);
					} else {
						// 插入操作
						save += applyDitributionService.insert(applyDitribution);
					}
				}
			}
			if (save > 0) {
				responseDTO.setMsg("分配成功");
			} else if (update > 0) {
				responseDTO.setMsg("更新成功");
			} else {
				responseDTO = new ResponseDTO(null, 400, "未知错误");
			}

		} catch (NumberFormatException e) {
			responseDTO = new ResponseDTO(null, 400, e.getMessage());
			e.printStackTrace();
		}
		return responseDTO;
	}

	/**
	 * 
	 * @Description :保存审核信息保存成功后，发送到app
	 * @author : zongzp
	 * @date :2018年1月16日下午1:30:26
	 * @version : 1.2.0
	 * @param applyAudit
	 * @return : ResponseDTO
	 */
	@RequestMapping("/saveAudit")
	@ResponseBody
	public ResponseDTO saveAudit(String status, String option, boolean isIdno, boolean isDriving, String applyId,
			String typeSelect, boolean isCarImage, boolean isCarInsurance, boolean isHouseCertificate) {
		Integer statu = 0;// 2 ：通过 3：未通过 能修改 4：未通过（拒绝 不支持修改）
		int stage = 0;
		int saveResult = 0;
		RequestDTO red = new RequestDTO();
		ResponseDTO responseDTO = new ResponseDTO(null, null);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ApplyAudit applyAudit = new ApplyAudit();
		// 获取当前登录用户
		SysUser sysUser = ShiroUserUtils.getCurrentShiroUser().getSysUser();
		int userId = sysUser.getId();
		SysRole sysRole = sysRoleService.selectByPrimaryKey(Integer.parseInt(sysUser.getRoleId()));
		String type = sysRole.getUserType();
		// 判断用户选择状态
		applyAudit.setApplyMainId(Integer.parseInt(applyId));
		applyAudit.setOpinion(option);
		if (status.equals("#jujue")) {
			statu = 4;
			applyAudit.setIsIdno("1");
			applyAudit.setIsDriving("1");
			applyAudit.setIsCarImage("1");
			applyAudit.setIsCarInsurance("1");
			applyAudit.setIsHouseCertificate("1");
		} else if (status.equals("#tongguo")) {
			statu = 2;
			applyAudit.setIsIdno("0");
			applyAudit.setIsDriving("0");
			applyAudit.setIsCarImage("0");
			applyAudit.setIsCarInsurance("0");
			applyAudit.setIsHouseCertificate("0");
		} else if (status.equals("#bohui")) {
			statu = 3;
			applyAudit.setIsIdno(isIdno ? "0" : "1");
			applyAudit.setIsDriving(isDriving ? "0" : "1");
			applyAudit.setIsCarImage(isCarImage ? "0" : "1");
			applyAudit.setIsCarInsurance(isCarInsurance ? "0" : "1");
			applyAudit.setIsHouseCertificate(isHouseCertificate ? "0" : "1");
		}
		// 封装applyAudit对象
		applyAudit.setStatus(statu);
		applyAudit.setAuditTime(new Date());
		applyAudit.setAuditUserId(String.valueOf(userId));

		Map<String, Object> userApplyInfo = applyMainService.getUserApplyInfoByApplyId(Integer.parseInt(applyId));

		// 封装返回app数据对象
		resultMap.put("idno", userApplyInfo.get("idno"));
		resultMap.put("applyId", userApplyInfo.get("applyId"));
		resultMap.put("creditQuota", null);
		resultMap.put("money", userApplyInfo.get("money"));
		resultMap.put("isDriving", applyAudit.getIsDriving());
		resultMap.put("isCarImage", applyAudit.getIsCarImage());
		resultMap.put("isCarInsurance", applyAudit.getIsCarInsurance());
		resultMap.put("isHouseCertificate", applyAudit.getIsHouseCertificate());
		resultMap.put("isIdno", applyAudit.getIsIdno());

		if (type.equals("SH")) {// 审核员登录
			stage = 0;
			applyAudit.setStage(stage);
			saveResult = applyAuditService.insert(applyAudit);// 保存审批信息
			resultMap.put("startDate", null);
			red.setData(resultMap);
			if (applyAudit.getStatus() == 3 || applyAudit.getStatus() == 4) {
				resultMap.put("status", applyAudit.getStatus());
				HttpClientUtil.doPostJson(appUrl + "/api/app/v146/result", JSONObject.fromObject(red).toString());// 发送审批结果//发送审批结果
		}else if(type.equals("SHM")){//审核经理登录
			if (applyAudit.getStatus() == 2) {
				resultMap.put("startDate", applyAudit.getAuditTime());
			} else {
				resultMap.put("startDate", null);
			}
		}
		stage = 1;
		applyAudit.setStage(stage);
		resultMap.put("status", statu);
		saveResult = applyAuditService.insert(applyAudit);// 保存审批信息
		red.setData(resultMap);
		String doPostJson = HttpClientUtil.doPostJson(appUrl + "/api/app/v146/result",
				JSONObject.fromObject(red).toString());// 发送审批结果
		logger.info("提交app返回结果是：{}", doPostJson);
		}
		if (saveResult > 0) {
			responseDTO = new ResponseDTO(null, "提交审批结果成功！");
		} else {
			responseDTO = new ResponseDTO(null, 400, "提交审批结果失败！");
		}
		logger.info("返回的结果是：{}", JSONObject.fromObject(responseDTO));
		return responseDTO;
	}

	@RequestMapping("/getAuditRecordList")
	@ResponseBody
	public ResponseDTO getAuditRecordList(String applyMainId) {
		// 审核员、审核时间、审核结果、审核意见
		ResponseDTO responseDTO = new ResponseDTO(null, null);
		try {
			Map<String, Object> result = applyAuditService.getAuditRecordList(applyMainId);
			responseDTO.setResults(result);
		} catch (Exception e) {
			responseDTO = new ResponseDTO(null, 400, e.getMessage());
			e.printStackTrace();
		}
		return responseDTO;
	}

}
